const fs = require('fs-extra');
const path = require('path');
const xlsx = require('node-xlsx');
const dayjs = require('dayjs');

const HOUSE_TYPE = require('../constant/index');
const TARGET_PATH = path.resolve(process.cwd(), './.data');
const PLATFORM = '贝壳找房';

const ershoufangMap = {
	title: '标题',
	address: '地址',
	addressUrl: '地址链接',
	houseDescText: '房屋描述',
	houseAreaText: '房屋面积',
	houseDirText: '房屋朝向',
	careInfo: '关注信息',
	publishDate: '发布日期',
	price: '单价/平米',
	totalPrice: '总价/万',
	tags: '标签'
};

const xinfangMap = {
	loupanName: '楼盘名称',
	loupanState: '楼盘状态',
	loupanType: '楼盘类型',
	loupanArea: '楼盘区域',
	loupanTown: '所在镇',
	loupanStreet: '街道',
	roomInfo: '户型信息',
	tags: '标签',
	price: '单价',
	unit: '单位',
	totalPrice: '总价/万',
};

const ershoufangchengjiaoMap = {
	title: '标题',
	target: '网址',
	img: '户型图图片',
	direction: '朝向',
	style: '装修样式',
	position: '位置',
	dealCycleeInfo: '成交信息',
	dealDate: '成交日期',
	totalPrice: '总价/万'
}

const formatErshoufang = key => ershoufangMap[key];
const formatXinfang = key => xinfangMap[key];
const formatErshoufangchengjiao = key => ershoufangchengjiaoMap[key];

const dataFilter = (type, item) => {
	if (type === HOUSE_TYPE.ER_SHOU_FANG) {
		return item.title;
	}

	if (type === HOUSE_TYPE.XIN_FANG) {
		return item.loupanName;
	}

	if (type === HOUSE_TYPE.ER_SHOU_FANG_CHENG_JIAO) {
		return item.title;
	}
}

const getTitleRow = (type, dataList) => {
	let titleRow = [];

	if (type === HOUSE_TYPE.ER_SHOU_FANG) {
		titleRow = Object.keys(dataList[0]).map(item => {
			return formatErshoufang(item);
		});
	}

	if (type === HOUSE_TYPE.XIN_FANG) {
		titleRow = Object.keys(dataList[0]).map(item => {
			return formatXinfang(item);
		});
	}

	if (type === HOUSE_TYPE.ER_SHOU_FANG_CHENG_JIAO) {
		titleRow = Object.keys(dataList[0]).map(item => {
			return formatErshoufangchengjiao(item);
		});
	}

	return titleRow;
}

module.exports = class Store {
	constructor() {
		this.name = 'store';
	}

	async save(type, city, area, dataList) {
		await fs.ensureDir(TARGET_PATH);

		let titleRow = [];

		titleRow = getTitleRow(type, dataList);

		const _dataList = dataList
			.filter(item => dataFilter(type, item))
			.map((data) => {
				const values = Object.values(data);

				return values.map(iv => {
					if (Array.isArray(iv)) {
						return iv.join(',');
					}

					return iv;
				});
			});

		_dataList.unshift(titleRow);

		const buffer = xlsx.build([{
			name: `${type}-${city}-${dayjs(Date.now()).format('YYYY-MM-DD')}`,
			data: _dataList
		}]);

		const writableStream = fs.createWriteStream(path.resolve(
			TARGET_PATH,
			`${PLATFORM}-${type}-${city}-${area}-${dayjs(Date.now()).format('YYYY-MM-DD-HH-mm')}.xlsx`
		));

		return new Promise((resolve, reject) => {
			let offset = 0;
			const chunkSize = 1024 * 5;

			function writeChunk() {
				if (offset < buffer.length) {
					const chunk = buffer.slice(offset, offset + chunkSize);

					writableStream.write(chunk, (err) => {
						if (err) {
							reject(err);
						} else {
							offset += chunkSize;

							writeChunk();
						}
					});
				} else {
					writableStream.end();

					resolve(_dataList.length - 1);
				}
			}

			writeChunk();
		});
	}
}